/**
 * User: yeqingzhou01
 * Date: 13-9-30
 * Time: 下午5:15
 */
var util = require('util');

/**
 * Enumeration arrays for types of errors
 * @type {{business: Array, repository: Array}}
 */
exports.errorsName = {
    syntax: 'AniSyntaxError',
    auth: 'AniAuthError',
    approval: 'AniApprovalError',
    rule: 'AniRuleError',
    data: 'AniDataError',
    invocation: 'AniInvocationError'
}

/**
 * Array of all errors
 */
var allErrorsArr = (function () {
    var finalArr = [];
    for (var oneErrKey in exports.errorsName) {
        finalArr.push(exports.errorsName[oneErrKey]);
    }
    return finalArr;
}());

/**
 * Error names array
 * @returns exports.AniError
 */
exports.getErrorInstance = function (errName, errMessage) {
    (function checkErrorExistence() {
        if (allErrorsArr.indexOf(errName) < 0) {
            throw exports.getErrorInstance(exports.errorsName.invocation, 'Error type not exists');
        }
    }());
//    return exports[errName](errMessage);
    var errMsg = '[' + errName + '] ' + errMessage;
    return new exports.AniError(
        errName,
        errMsg,
        function(){}     //constructor
    );
}
/**
 * Construct encapsulated JS basic error
 * @param name
 * @param msg
 * @param constr
 * @constructor
 */
exports.AniError = function (name, msg, constr) {
    exports.AniError.prototype.name = name;
    Error(this, constr || this);
    this.message = msg || 'Error';
}
util.inherits(exports.AniError, Error);

///**
// * Define all error classes
// */
//(function () {
//    for (var errKey in exports.errorsName) {
//        var oneErrName = exports.errorsName[errKey];
//        util.log(oneErrName);
//        exports[oneErrName] = function (msg) {
//            util.log('error instance with message [ ' + msg + ' ] initializing...');
//            exports[oneErrName].super_.call(this, oneErrName, msg, this.constructor);
//            util.log('error instance initialized');
//        }
//        util.inherits(exports[oneErrName], exports.AniError);
//        util.log('error instance of [' + oneErrName + '] initialized.');
//    }
//}());

exports.checkError = function (oneData, errBack, next) {
    if(oneData instanceof Error) {
        util.error(oneData.message);
        errBack(oneData);
    }
    next(oneData);
}
